/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\QuotaManage\QuotaImport\List\components\PlanTable.tsx
 * @Date: 2021-09-27 15:30:46
 * @LastEditTime: 2023-03-29 23:25:13
 */

import React from 'react'
import { columnRenders, http, UdTable, validators, UdDatePicker, UdForm } from '@/lib'
import UdSelect from '@/components/UdFormControls/UdSelect'
import { message, Modal, Button, Input, Spin, TreeSelect } from 'antd'
import { randomNumber } from '@/utils/methods'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import quotaApis from '@/apis/AboutQuota'
import apis from '@/apis'
import '../style.scss'
import TextArea from 'antd/lib/input/TextArea'
import dayjs from 'dayjs'
import moment from 'moment'
const confirm = Modal.confirm
const { TreeNode } = TreeSelect
export default class PlanTable extends React.Component<any, any> {
  planForm: WrappedFormUtils
  state = {
    specialBrandList: [],
    loading: false,
    prodBarCodeList: [],
    planListData: [],
    treeDataList: [],
    baseItem: {
      id: randomNumber(5),
      stageName: null,
      stageStatus: 'UNEXECUTED',
      stageDays: null,
      stageBeginTime: null,
      stageEndTime: null,
      belongAreaCodes: [],
    },
    planListColumns: [
      {
        title: '序号',
        key: 'description',
        dataIndex: 'description',
        width: 50,
        render: (text, record, index) => {
          return index + 1
        },
      },
      {
        title: '考核阶段名称',
        key: 'stageName',
        dataIndex: 'stageName',
        width: 200,
        render: (text, record, index) => (
          <TextArea
            placeholder="请输入考核阶段名称"
            value={record.stageName}
            maxLength={250}
            onChange={e => {
              this.handChange({ type: 'text', value: e.target.value, record, index, key: 'stageName' })
            }}
          />
        ),
      },
      {
        title: '片区',
        key: 'belongAreaCodes',
        dataIndex: 'belongAreaCodes',
        width: 340,
        render: (text, record, index) => (
          <TreeSelect
            showCheckedStrategy={TreeSelect.SHOW_ALL}
            showSearch
            treeNodeFilterProp="title"
            style={{ width: '100%' }}
            value={record.belongAreaCodes}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择片区"
            allowClear
            treeCheckable={true}
            maxTagCount={5}
            onChange={value => {
              this.handChange({ type: 'text', value, record, index, key: 'belongAreaCodes' })
            }}
          >
            {this.mapTree(this.state.treeDataList)}
          </TreeSelect>
        ),
      },
      {
        title: '考核天数',
        key: 'stageDays',
        dataIndex: 'stageDays',
        width: 200,
        render: (text, record, index) => (
          <Input
            readOnly={true}
            placeholder="根据所选时间自动计算考核天数"
            value={record.stageDays}
            onChange={e => {
              this.handChange({ type: 'text', value: e.target.value, record, index, key: 'stageName' })
            }}
          />
        ),
      },
      {
        title: '开始时间',
        key: 'stageBeginTime',
        dataIndex: 'stageBeginTime',
        width: 200,
        render: (text, record, index) => (
          <UdDatePicker
            allowClear={false}
            format="YYYY-MM-DD"
            value={record.stageBeginTime ? moment(record.stageBeginTime) : null}
            style={{ width: '100%' }}
            onChange={(date: any) => {
              this.handChange({ type: 'date', value: date, record, index, key: 'stageBeginTime' })
            }}
          />
        ),
      },
      {
        title: '结束时间',
        key: 'stageEndTime',
        dataIndex: 'stageEndTime',
        width: 200,
        render: (text, record, index) => (
          <UdDatePicker
            disabledDate={current => {
              return this.disabledDate(current, index, 'stageEndTime')
            }}
            allowClear={false}
            format="YYYY-MM-DD"
            value={record.stageEndTime ? moment(record.stageEndTime) : null}
            style={{ width: '100%' }}
            disabled={record.stageBeginTime == null}
            onChange={(date: any) => {
              this.handChange({ type: 'date', value: date, record, index, key: 'stageEndTime' })
            }}
          />
        ),
      },
      {
        title: '执行状态',
        key: 'stageStatus',
        dataIndex: 'stageStatus',
        width: 100,
        render: (text, record, index) => {
          let stageStatus = {
            EXECUTED: '已执行',
            EXECUTION: '执行中',
            UNEXECUTED: '待执行',
          }
          return stageStatus[record.stageStatus]
        },
      },
      {
        title: '操作',
        width: 60,
        render: columnRenders.operate([
          {
            title: '删除',
            show: (text: any, record: any, index: number) => {
              return record.stageStatus === 'UNEXECUTED'
            },
            action: (text: any, record: any, index: number) => {
              confirm({
                title: '确定要删除该项吗？',
                onOk: () => {
                  return this.delPlanTableItem(record, index)
                },
              })
            },
          },
        ]),
      },
    ],
  }
  /**片区Tree的数据处理 */
  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }
  /** 获取需要特殊处理的品牌公司*/
  private handGetSpecialBrandList = () => {
    http.get(quotaApis.getSpecialBrandList).then(res => {
      let data = res?.data ?? []
      this.setState({ specialBrandList: data })
    })
  }

  /**
   * @description:时间是否可选
   * @param {*} current
   * @param {*} index
   * @param {*} key
   * @return {*} 返回Boolean值,true是不可选,false是可选
   */
  private disabledDate = (current, index, key) => {
    if (key === 'stageEndTime') {
      return (
        current && current.isBefore(dayjs(this.state.planListData[index].stageBeginTime).format('YYYY-MM-DD'), 'day')
      )
    }
  }

  /**选择品牌公司 */
  private handChangeBrandCode = params => {
    this.setState({ planListData: [], treeDataList: [], prodBarCodeList: [] }, () => {
      this.planForm.setFieldsValue(
        {
          prodBarcode: undefined,
        },
        () => {
          this.getProdBarList(params)
          this.getBelongAreaList(params)
        }
      )
    })
  }

  private handChange = (params: any): void => {
    const { type, key, value, record, index } = params
    let diffDay = 0
    if (type === 'date') {
      record[key] = dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    } else {
      record[key] = value
    }
    if (type === 'date' && record.stageEndTime && record.stageBeginTime) {
      diffDay = dayjs(record.stageEndTime).add(1, 'd').diff(dayjs(record.stageBeginTime), 'day')
      record['stageDays'] = diffDay
    }
    const planListData = [...this.state.planListData]
    planListData[index] = record
    this.setState({ planListData })
  }
  /**新增考核阶段按钮 */
  public addPlanTableItem = () => {
    let { brand } = this.planForm.getFieldsValue()
    if (!brand?.key) {
      message.warn('请先选择品牌公司')
      return false
    }
    const planListData = [...(this?.state?.planListData ?? [])]
    if (planListData.length !== 0) {
      let item = planListData[planListData.length - 1]

      if (!item.stageBeginTime) {
        message.warn('请补全考核计划开始时间')
        return false
      }
      if (!item.stageEndTime) {
        message.warn('请补全考核计划结束时间')
        return false
      }
    }
    let item = { ...this.state.baseItem }
    item.id = randomNumber(5)
    planListData.push(item as any)
    this.setState({ planListData })
  }

  private delPlanTableItem = (record: any, index: number) => {
    this.state.planListData.splice(index, 1)
    this.setState({ planListData: this.state.planListData })
  }
  /**确认提交 */
  private onOk = e => {
    let { specialBrandList } = this.state
    this.planForm.validateFields((err, values) => {
      if (!err) {
        let msg = '添加成功'
        let params = {}
        if (this.props.record) {
          params = this.props.record
          msg = '修改成功'
        } else {
          params['brandCode'] = values.brand.key
          params['brandName'] = values.brand.label
          params['stageYear'] = values.stageYear
          params['prodBarcode'] = values.prodBarcode.join(',')
        }
        const planListData = [...this.state.planListData]
        if (planListData.length === 0) {
          message.warn('请添加考核阶段')
          return false
        }

        for (let item of planListData) {
          if (!item.stageName) {
            message.warn('请补全考核阶段名称')
            return false
          }
          if (!item.stageBeginTime) {
            message.warn('请补全考核计划开始时间')
            return false
          }
          if (!item.stageEndTime) {
            message.warn('请补全考核计划结束时间')
            return false
          }
          if (specialBrandList.includes(values?.brand?.key) && item.belongAreaCodes.length === 0) {
            message.warn('请补全考核计划片区')
            return false
          }
        }
        params['quotaApplyPlanSaveReqVos'] = planListData
        this.setState({ loading: true })
        http
          .post(quotaApis.saveOrUpdateQuota, params)
          .then(res => {
            message.success(msg)
            e.close()
            this.props.handQuery()
          })
          .finally(() => {
            this.setState({
              loading: false,
            })
          })
      } else {
        console.log(err)
      }
    })
  }
  /**编辑回显 */
  private getPlanTableData = (id: string | number) => {
    this.setState({ loading: true })
    http
      .get(quotaApis.getPlanDetail, {
        params: { id },
      })
      .then(res => {
        const { quotaApplyPlanManageRespVos: planListData } = res.data
        this.setState({ planListData })
      })
      .finally(() => {
        this.setState({ loading: false })
      })
  }
  /**根据选中的品牌公司获取配额品项 */
  private getProdBarList = (value: string | Record<string, any>, callBack?: any) => {
    http
      .get(quotaApis.getProdBarList, {
        params: { brandCode: typeof value === 'string' ? value : value.key },
      })
      .then(res => {
        const { data = [] } = res
        const prodBarCodeList = data.map(item => ({ value: item.code, title: item.name }))
        this.setState({ prodBarCodeList }, callBack)
      })
  }
  /**根据选中的品牌公司获取片区 */
  private getBelongAreaList = (value: string | Record<string, any>, callBack?: any) => {
    http
      .get(apis.getTreeByUser, {
        params: { organizationCode: typeof value === 'string' ? value : value.key },
      })
      .then(res => {
        this.setState(
          {
            treeDataList: res?.data?.children || [],
          },
          callBack
        )
      })
  }

  componentDidMount() {
    this.handGetSpecialBrandList()
    const { record } = this.props
    if (record) {
      this.planForm.setFieldsValue(
        {
          stageYear: record.stageYear,
          brand: { label: record.brandName, key: record.brandCode },
          prodBarcode: record?.prodBarcode?.split(',') ?? [],
        },
        () => {
          this.getProdBarList(record.brandCode)
          this.getBelongAreaList(record.brandCode)
          this.getPlanTableData(record.id)
        }
      )
    }
  }

  render() {
    const { stageYearList = [], brandList = [] } = this.props
    let { specialBrandList } = this.state
    let { brand } = this?.planForm?.getFieldsValue?.() ?? {}
    let addBtn = (
      <Button type="primary" onClick={this.addPlanTableItem} className="addPlanTableItemBtn">
        新增考核阶段
      </Button>
    )
    return (
      <>
        <Spin spinning={this.state.loading}>
          <UdForm
            getForm={form => (this.planForm = form)}
            items={[
              {
                label: '品牌公司',
                id: 'brand',
                rules: [validators.required],
                labelCol: { span: 2 },
                wrapperCol: { span: 8 },
                render: (
                  <UdSelect
                    showSearch
                    labelInValue
                    disabled={this.props.record != null}
                    options={brandList}
                    onChange={value => this.handChangeBrandCode(value)}
                  />
                ),
              },
              {
                id: 'stageYear',
                label: '考核年度',
                rules: [validators.required],
                labelCol: { span: 2 },
                wrapperCol: { span: 8 },
                render: (
                  <UdSelect
                    disabled={this.props.record != null}
                    showSearch
                    options={stageYearList}
                    optionFilterProp="children"
                  />
                ),
              },
              {
                id: 'prodBarcode',
                label: '选择配额品项',
                rules: [validators.required],
                labelCol: { span: 2 },
                wrapperCol: { span: 8 },
                render: (
                  <UdSelect
                    mode="multiple"
                    disabled={this.props.record != null}
                    showSearch
                    options={this.state.prodBarCodeList}
                  />
                ),
              },
            ]}
          />
          {addBtn}
          <UdTable
            columns={this.state.planListColumns.filter(element => {
              //新增不显示执行状态
              if (element.key === 'stageStatus' && this?.props?.record == null) {
                return false
              }
              if (element.key === 'belongAreaCodes' && specialBrandList.includes(brand?.key) === false) {
                return false
              }
              return true
            })}
            dataSource={this.state.planListData}
            pagination={false}
            rowKey="id"
          />
        </Spin>
      </>
    )
  }
}
